//
//  WaterSearchViewController.m
//  wsgz
//
//  Created by huck on 2017/5/6.
//  Copyright © 2017年 BoingPay. All rights reserved.
//

#import "WaterSearchViewController.h"
#import "AppUtils.h"
#import "HomeManager.h"
#import "MJRefreshFooterView.h"
#import "WaterSearchTableViewCell.h"


#define kMoreBtnTag 9999
static NSString* s_waterSearchListCellIdentifier = @"WaterSearchListCellIdentifier";


@interface WaterSearchViewController ()<UIScrollViewDelegate,UITableViewDelegate,UITableViewDelegate>

@property (nonatomic, retain) MJRefreshFooterView *refreshFooterView;

@property (nonatomic ,copy) NSString *regionId; //保存乡镇名称
@property (nonatomic ,copy) NSString *wLevelId; //保存水体等级
@property (nonatomic ,copy) NSString *wquestion;//保存问题分类

@property (nonatomic) NSInteger pageNO;//分页

@end

@implementation WaterSearchViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    [self initSubview];
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [_searchTextField resignFirstResponder];
    _moreCountryView.hidden = YES;
}

-(void)viewDidDisappear:(BOOL)animated
{
    [super viewDidDisappear:animated];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [_searchTextField resignFirstResponder];
    _moreCountryView.hidden = YES;
}

- (void)dealloc
{
    [_refreshFooterView free];
}


-(void)initSubview
{
    self.title = @"水体搜索";
    [self.view addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(hideInput1)]];
    
    NSArray *containers = @[_countryViewContainner,_waterTypeContainner,_questionTypeContainner];
    for(UIView *container in containers){
        for(UIView *view in container.subviews){
            if([view isKindOfClass:[UIButton class]]){
                UIButton *btn = (UIButton *)view;
                if(btn.tag != kMoreBtnTag){
                    //设置按钮类型
                    [self initBtnStyle:btn];
                }
            }
        }
    }
    
    [self initMoreCountryView];
    [self initDefaultCountry];
    [self initWaterLevelBtn];
    [self initQuestionTypeBtn];
    
    [_searchListTableView registerNib:[UINib nibWithNibName:@"WaterSearchTableViewCell" bundle:nil] forCellReuseIdentifier:s_waterSearchListCellIdentifier];
    
    __weak id weakSelf = self;
    _refreshFooterView = [MJRefreshFooterView footer];
    _refreshFooterView.scrollView = _searchListTableView;
    _refreshFooterView.beginRefreshingBlock = ^(MJRefreshBaseView *refreshView){
        [weakSelf pullUpRefresh];
    };
    [self initData];
}

- (void)initData
{
    _pageNO = 1;
    _refreshFooterView.stopRefresh = NO;
    [_refreshFooterView setStopRefresh:NO];
    [self requestData:YES showLoading:YES];
    [_searchListTableView setContentOffset:CGPointMake(0, 0)];
}

- (void)requestData:(BOOL)reset showLoading:(BOOL)showLoading
{
    //获取一连串参数
    NSString *wName = [AppUtils trim:_searchTextField.text];
    
    if (showLoading) {
        [Toast loading];
    }

    [[HomeManager sharedInstance] requestSearchWater:wName wLevelId:_wLevelId regionId:_regionId wquestion:_wquestion page:_pageNO reset:reset complete:^(BOOL success, BOOL hasMore) {
        if (_refreshFooterView) {
            [_refreshFooterView endRefreshing];
            [_refreshFooterView setStopRefresh:!hasMore];
        }
        if (showLoading) {
            [Toast loaded];
        }
        if (!reset) {
            [_refreshFooterView endRefreshing];
        }
        if(hasMore){
            _pageNO++;
        }
        [_searchListTableView reloadData];
    }];
}

//上拉刷新
- (void)pullUpRefresh
{
    if ([AppUtils hasConnected:YES]) {
        [self requestData:NO showLoading:NO];
    }
    else {
        [_refreshFooterView endRefreshing];
    }
}

//设置默认乡镇
-(void)initDefaultCountry
{
    NSArray *arr = [HomeManager sharedInstance].regionList;
    if(arr.count>0){
        RegionInfoData *firstRegion = arr[0];
        NSString *nameValue = firstRegion.regionName;
        if(nameValue.length>6){
            nameValue = [nameValue substringToIndex:6];
        }
        _btn1.accessibilityValue = firstRegion.regionId;
        [_btn1 setTitle:nameValue forState:UIControlStateNormal];
        [_btn1 setTitle:nameValue forState:UIControlStateHighlighted];
        [_btn1 setTitle:nameValue forState:UIControlStateSelected];
        CGFloat nameLen = [AppUtils labelSizeWithString:nameValue font:[UIFont systemFontOfSize:13]  maxSize:CGSizeMake(SCREEN_WIDTH, 22)].width;
        nameLen = nameLen+12<50?50:nameLen+12; //最小50
        _btn1W.constant = nameLen;
        _btn1.hidden = NO;
        if([firstRegion.regionId isEqualToString:LOGIN_USER.beregionCode]){
            _btn1.selected = YES;
            [self checkBtn:_btn1];
            _regionId = firstRegion.regionId;
            UIButton *firstbtn =  [_countryViewContainner viewWithTag:300];
            firstbtn.selected = NO;
            [self checkBtn:firstbtn];
        }
    }else{
        _btn1.hidden = YES;
        _btn1W.constant = 0;
    }
    if(arr.count>1){
        RegionInfoData *secondRegion = arr[1];
        NSString *nameValue = secondRegion.regionName;
        if(nameValue.length>6){
            nameValue = [nameValue substringToIndex:6];
        }
        _btn2.accessibilityValue = secondRegion.regionId;

        [_btn2 setTitle:nameValue forState:UIControlStateNormal];
        [_btn2 setTitle:nameValue forState:UIControlStateHighlighted];
        [_btn2 setTitle:nameValue forState:UIControlStateSelected];
        CGFloat nameLen = [AppUtils labelSizeWithString:nameValue font:[UIFont systemFontOfSize:13]  maxSize:CGSizeMake(SCREEN_WIDTH, 22)].width;
        nameLen = nameLen+12<50?50:nameLen+12; //最小50
        _btn2W.constant = nameLen;
        _btn2.hidden = NO;
        if([secondRegion.regionId isEqualToString:LOGIN_USER.beregionCode]){
            _btn2.selected = YES;
            [self checkBtn:_btn2];
            _regionId = secondRegion.regionId;
            UIButton *firstbtn =  [_countryViewContainner viewWithTag:300];
            firstbtn.selected = NO;
            [self checkBtn:firstbtn];
        }

    }else{
        _btn2.hidden = YES;
        _btn2W.constant = 0;
    }
    _moreBtn.hidden = arr.count<=2;

}

//初始化更多乡镇
-(void)initMoreCountryView
{
    _moreCountryView.layer.borderWidth = 1;
    _moreCountryView.layer.borderColor = [UIColor colorWithString:COLOR_DBD9DE].CGColor;

    [AppUtils clearSubView:_moreCountryView];

    CGFloat margin = 5;
    CGFloat btnH = 22;
    CGFloat totalW = SCREEN_WIDTH-40-margin*2;
    CGFloat offx = margin;
    CGFloat offy = margin;
    int i = 301;
    for(RegionInfoData *infoData in [HomeManager sharedInstance].regionList){
        if ([AppUtils isEmpty:infoData.regionName]) {
            continue;
        }
        NSString *nameValue = infoData.regionName;
        if(nameValue.length>15){
            nameValue = [nameValue substringToIndex:15];
        }
        
        CGFloat nameLen = [AppUtils labelSizeWithString:nameValue font:[UIFont systemFontOfSize:13]  maxSize:CGSizeMake(totalW, btnH)].width;
        nameLen = nameLen+12<50?50:nameLen+12; //最小50
        if (offx + nameLen  > totalW) {
            offx = margin;
            offy+=btnH+margin;
        }
        
        [self addBtnInView:_moreCountryView title:nameValue tag:i accessValue:infoData.regionId frame:CGRectMake(offx, offy, nameLen, btnH) hasBorder:NO];
        i++;
        offx += nameLen + margin;
    }
    
    offy+=btnH+5;
    _moreCountryView.contentSize = CGSizeMake(SCREEN_WIDTH-40, offy);
}

//初始化水体等级分类的按钮
-(void)initWaterLevelBtn
{
    for(UIView *view in _waterTypeContainner.subviews){
        if([view isKindOfClass:[UIButton class]]){
            UIButton *btn = (UIButton *)view;
            if(btn.tag !=200){
                [btn removeFromSuperview];
            }
        }
    }

    CGFloat X0 = 60;
    CGFloat marginX = 10;
    CGFloat marginY = 3;
    CGFloat btnH = 22;
    CGFloat totalW = SCREEN_WIDTH-55-60;
    CGFloat offx = X0;
    CGFloat offy = marginY;
    int i = 201;
    for(SystemInfoData *infoData in [HomeManager sharedInstance].waterClassList){
        if ([AppUtils isEmpty:infoData.systemLabel]) {
            continue;
        }
        NSString *nameValue = infoData.systemLabel;
        if(nameValue.length>10){
            nameValue = [nameValue substringToIndex:10];
        }
        
        CGFloat nameLen = [AppUtils labelSizeWithString:nameValue font:[UIFont systemFontOfSize:13]  maxSize:CGSizeMake(totalW, btnH)].width;
        nameLen = nameLen+12<50?50:nameLen+12; //最小50
        if (offx + nameLen  > totalW) {
            offx = X0;
            offy+=btnH+marginY;
        }
        
        [self addBtnInView:_waterTypeContainner title:nameValue tag:i accessValue:infoData.systemValue frame:CGRectMake(offx, offy, nameLen, btnH) hasBorder:YES];
        i++;
        offx += nameLen + marginX;
    }
    
    offy+=btnH+marginY;
    _waterTypeContainnerH.constant = offy;
}

//初始化问题分类按钮的值
-(void)initQuestionTypeBtn
{
    for(UIView *view in _questionTypeContainner.subviews){
        if([view isKindOfClass:[UIButton class]]){
            UIButton *btn = (UIButton *)view;
            NSInteger tag = btn.tag -101;
            if(tag>=0){
                btn.accessibilityValue = [AppUtils toStr:tag];
            }
        }
    }
}

//生成一个按钮
-(UIButton *)addBtnInView:(UIView*)view title:(NSString*)title tag:(NSInteger)tag accessValue:(NSString *)value frame:(CGRect)frame hasBorder:(BOOL)hasBorder
{
    UIButton *btn = [[UIButton alloc] initWithFrame:frame];
    btn.tag = tag;
    btn.accessibilityValue = value;
    if([value isEqualToString:LOGIN_USER.beregionCode]){
        btn.selected = YES;
        _regionId = value;
        UIButton *firstbtn =  [_countryViewContainner viewWithTag:300];
        firstbtn.selected = NO;
        [self checkBtn:firstbtn];
    }
    btn.layer.masksToBounds = YES;
    btn.layer.cornerRadius = 2;
    btn.titleLabel.font = [UIFont systemFontOfSize:13];
    [btn setTitle:title forState:UIControlStateNormal];
    [btn setTitle:title forState:UIControlStateHighlighted];
    [btn setTitle:title forState:UIControlStateSelected];
    [btn setTitleColor:[UIColor colorWithString:COLOR_17A4FF] forState:UIControlStateNormal];
    [btn setTitleColor:[UIColor colorWithString:COLOR_17A4FF] forState:UIControlStateNormal];
    [btn setTitleColor:[UIColor colorWithString:COLOR_FFFFFF] forState:UIControlStateSelected];
    if(hasBorder){
        [self initBtnStyle:btn];
    }else{
        [btn addTarget:self action:@selector(selectBtn:) forControlEvents:UIControlEventTouchUpInside];
    }
    [self checkBtn:btn];
    [view addSubview:btn];
    return btn;
    
}

//初始化按钮样式
- (void)initBtnStyle:(UIButton *)btn
{
    btn.layer.borderWidth = 1;
    btn.layer.borderColor = [UIColor colorWithString:COLOR_17A4FF].CGColor;
    [btn addTarget:self action:@selector(selectBtn:) forControlEvents:UIControlEventTouchUpInside];
    
}

//按钮选中切换,同时开始搜索
-(void)selectBtn:(UIButton *)btn
{
    NSInteger tag = btn.tag;
    NSArray *containers = @[];
    if(tag>=300){
        _regionId = btn.accessibilityValue;
        containers = @[_countryViewContainner,_moreCountryView];
    }else if(tag>=200){
        containers = @[_waterTypeContainner];
        _wLevelId = btn.accessibilityValue;
    }else if(tag>=100){
        _wquestion = btn.accessibilityValue;
        containers = @[_questionTypeContainner];
    }
    for(UIView *container in containers){
        NSArray *bratherView = [container subviews];
        for(UIView *view in bratherView){
            if([view isKindOfClass:[UIButton class]]){
                UIButton *b = (UIButton *)view;
                if(b.tag != kMoreBtnTag){
                    b.selected = b.tag ==tag;
                    [self checkBtn:b];
                }
            }
        }
    }
    [self initData];
}

//设置按钮背景颜色
-(void)checkBtn:(UIButton *)btn{
    if(btn.selected){
        btn.backgroundColor = [UIColor colorWithString:COLOR_17A4FF];
    }else{
        btn.backgroundColor = [UIColor colorWithString:COLOR_FFFFFF];
    }
}

-(void)hideInput1
{
    [self hideInput];
    _moreCountryView.hidden = YES;
}

- (IBAction)moreCountryBtnClick:(UIButton *)sender
{
    _moreCountryView.hidden = !_moreCountryView.hidden;
}


- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [super textFieldShouldReturn:textField];
    [self initData];
    return YES;
}

#pragma mark UIScrollViewDelegate
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    [self hideInput];
    // 滚动到底部，自动加载
    if([AppUtils isScrollToBottom:scrollView] && ![_refreshFooterView isRefreshing] && !_refreshFooterView.stopRefresh) {
        [_refreshFooterView beginRefreshing];
    }
}

#pragma mark UITableDelegate

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [HomeManager sharedInstance].waterInfoList.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 55;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    WaterSearchTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:s_waterSearchListCellIdentifier];
    if (nil == cell) {
        return nil;
    }
    
    WaterInfoData *data = [[HomeManager sharedInstance].waterInfoList objectAtIndex:indexPath.row];
    
    [cell setInfo:data index:indexPath.row];
    return cell;
}




@end
